package com.huidu.bitrade.consumer;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.huidu.bitrade.config.MQTraceAspect;
import com.huidu.bitrade.constant.BooleanEnum;
import com.huidu.bitrade.dao.MemberWalletDao;
import com.huidu.bitrade.entity.Coin;
import com.huidu.bitrade.entity.MemberWallet;
import com.huidu.bitrade.service.CoinService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.math.BigDecimal;
import java.util.List;

/**
 * @author QQ：97095646
 * @date 2020年02月08日
 */
@Slf4j
@Component
public class CoinConsumer {

    @PersistenceContext
    protected EntityManager em;

    @Autowired
    private MemberWalletDao memberWalletDao;
    @Autowired
    private CoinService coinService;

    /**
     * 添加新币种，为用户增加钱包
     *
     * @param content
     */
    @Trace(operationName = "consumerTag-CoinConsumer-handle")
    @KafkaListener(topics = {"coin-start"})
    public void handle(String content) {
        log.info("handle coin-start,data={}", content);
        MQTraceAspect.consumerData("coin-start",content,"添加新币种，为用户增加钱包");
        if (StringUtils.isEmpty(content)) {
            return;
        }
        JSONObject json = JSON.parseObject(content);
        if (json == null) {
            return;
        }
        String coinName = json.getString("name");
        Coin coin = coinService.findOne(coinName);
        if (coin != null && coin.getEnableRpc().equals(BooleanEnum.IS_TRUE)) {
            List<MemberWallet> list = memberWalletDao.findDataNotCoin(coinName);
            for (int i = 0; i < list.size(); i++) {
                MemberWallet wallet = new MemberWallet();
                wallet.setCoin(coin);
                wallet.setMemberId(list.get(i).getMemberId());
                wallet.setBalance(new BigDecimal(0));
                wallet.setFrozenBalance(new BigDecimal(0));
                wallet.setAddress("");
                em.persist(wallet);
                if (i % 1000 == 0 || i == list.size() - 1) {
                    em.flush();
                    em.clear();
                }
            }
            em.flush();
            em.clear();
        }
    }
}
